//
//  HomeViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/9/19.
//

import UIKit
import SwiftyJSON
import Toast_Swift
import Alamofire
import AlamofireImage

class HomeViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    @IBOutlet weak var emptyBgView: EmptyView!
    
    var rootArr = JSON.init(parseJSON: "[]")
    @IBOutlet weak var rootBgView: UIView!
    private let rootScrollView: UIScrollView = UIScrollView.init()
    var rootActiveIndex = 0
    
    var secondArr = JSON.init(parseJSON: "[]")
    @IBOutlet weak var secondTableView: UITableView!
    var secondActiveIndex = 0
    @IBOutlet weak var secondTabelViewWidth: NSLayoutConstraint!
    @IBOutlet weak var secondActiveTitle: UILabel!
    
    var thirdArr = JSON.init(parseJSON: "[]")
    @IBOutlet weak var thirdBgView: UIView!
    @IBOutlet weak var thirdBgViewHeight: NSLayoutConstraint!
    @IBOutlet weak var thirdBgViewBottomHeight: NSLayoutConstraint!
    private let thirdScrollView: UIScrollView = UIScrollView.init()
    var thirdActiveIndex = 0
    
    var page = 1
    var courseArr = JSON.init(parseJSON: "[]")
    @IBOutlet weak var courseTableView: UITableView!
    var currentCoursePid = ""
    
    @IBOutlet weak var contentBgView: UIView!
    
    @objc func handleToScan() {
        let scan = ScanViewController.init()
        scan.scanResBlock = { scanRes in
            self.toLoginTv(scanRes)
        }
        
        let nav = UINavigationController.init(rootViewController: scan)
        nav.modalPresentationStyle = .fullScreen
        
        self.present(nav, animated: true)
    }
    
    func toLoginTv(_ qrcode: String) {
        var params = JSON.init(parseJSON: "{}")
        params["code"].string = qrcode
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.logined_to_login_tv_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                UserInfo.sharedInstance.clearUserAutoLoginKey()
                UserInfo.sharedInstance.toLogin("normal")
            }
        }
    }
    
    // MARK: 搜索
    @IBAction func handleSearch(_ sender: Any) {
        let search = UtilManager.sharedInstance.getVCFromSB(identifier: "SearchViewController") as! SearchViewController
        self.navigationController?.pushViewController(search, animated: true)
    }
    
    // MARK: 获取不同分类数据
    func handleGetCategoryList(type: String, pid: String = "") {
        emptyBgView.isHidden = true
        
        page = 1
        courseArr = JSON.init(parseJSON: "[]")
        courseTableView.reloadData()
        
        var params = JSON.init(parseJSON: "{}")
        params["page"].string = "1"
        params["size"].string = "100"
        if (pid != "") {
            params["pid"].string = pid
        }
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.category_list_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                
                if (type == "root") {
                    self.rootArr = result["data"]["list"]
                    self.reloadRootView()
                    
                    self.secondTabelViewWidth.constant = 0
                    self.secondActiveIndex = 0
                    self.secondArr = JSON.init(parseJSON: "[]")
                    self.secondTableView.reloadData()
                    self.secondActiveTitle.text = ""
                    
                    self.thirdActiveIndex = 0
                    self.thirdArr = JSON.init(parseJSON: "[]")
                    self.reloadThirdView()
                    
                    self.page = 1
                    self.courseArr = JSON.init(parseJSON: "[]")
                    self.courseTableView.reloadData()
                    
                    // 获取二级分类
                    if (self.rootArr.count != 0) {
                        self.handleGetCategoryList(type: "second", pid: self.rootArr[0].dictionaryObject!["id"] as! String)
                    } else {
                        self.emptyBgView.isHidden = false
                    }
                } else if (type == "second") {
                    self.secondActiveIndex = 0
                    self.secondArr = result["data"]["list"]
                    
                    self.thirdActiveIndex = 0
                    self.thirdArr = JSON.init(parseJSON: "[]")
                    self.reloadThirdView()
                    
                    self.page = 1
                    self.courseArr = JSON.init(parseJSON: "[]")
                    self.courseTableView.reloadData()
                    
                    if (self.secondArr.count != 0) {
                        self.secondTabelViewWidth.constant = 76
                        self.secondTableView.reloadData()
                        // 获取三级分类
                        self.handleGetCategoryList(type: "third", pid: self.secondArr[0].dictionaryObject!["id"] as! String)
                    } else {
                        self.secondTabelViewWidth.constant = 0
                        self.secondActiveIndex = 0
                        self.secondArr = JSON.init(parseJSON: "[]")
                        self.secondTableView.reloadData()
                        self.secondActiveTitle.text = ""
                        
                        self.currentCoursePid = pid
                        self.handleGetCourseListData()
                    }
                    
                } else if (type == "third") {
                    self.thirdActiveIndex = 0
                    self.thirdArr = result["data"]["list"]
                    self.reloadThirdView()
                    
                    if (self.thirdArr.count == 0) {
                        self.currentCoursePid = pid
                    } else {
                        self.currentCoursePid = self.thirdArr[self.thirdActiveIndex]["id"].stringValue
                    }
                    self.handleGetCourseListData()
                }
            }
        }
    }
    
    // MARK: 获取课程列表
    func handleGetCourseListData() {
        var params = JSON.init(parseJSON: "{}")
        params["page"].string = String(page)
        params["size"].string = "10"
        params["cid"].string = currentCoursePid
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.course_list_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                if self.page == 1 {
                    self.courseArr = result["data"]["list"]
                    self.courseTableView.mj_header?.endRefreshing()
                } else {
                    
                    var list = self.courseArr.arrayValue
                    for (_, item) in result["data"]["list"] {
                        list.append(item)
                    }
                    self.courseArr = JSON.init(list)
                    self.courseTableView.mj_footer?.endRefreshing()
                }
                
                if result["data"]["list"].arrayValue.count < 10 {
                    self.courseTableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.courseTableView.mj_footer?.endRefreshing()
                }
                
                self.courseTableView.reloadData()
            }
        }
    }
    
    // MARK: - 一级分类
    func reloadRootView() {
        let bgView = rootScrollView
        for view in bgView.subviews {
            view.removeFromSuperview()
        }
        
        for index in 0..<rootArr.count {
            let itemBgView = UIView.init()
            rootScrollView.addSubview(itemBgView)
            if index == 0 {
                itemBgView.snp.makeConstraints { (make) in
                    make.top.bottom.equalToSuperview()
                    make.left.equalToSuperview().offset(24)
                    make.height.equalTo(rootBgView.snp.height)
                }
            } else if index == rootArr.count - 1 {
                itemBgView.snp.makeConstraints { (make) in
                    make.right.equalToSuperview().offset(-24)
                    make.top.bottom.equalToSuperview()
                    make.left.equalTo(rootScrollView.subviews[index - 1].snp.right).offset(24)
                    make.height.equalTo(rootBgView.snp.height)
                }
            } else {
                itemBgView.snp.makeConstraints { (make) in
                    make.top.bottom.equalToSuperview()
                    make.left.equalTo(rootScrollView.subviews[index - 1].snp.right).offset(24)
                    make.height.equalTo(rootBgView.snp.height)
                }
            }
            
            let btn = UIButton.init(type: .custom)
            btn.setTitle(rootArr[index]["name"].stringValue, for: .normal)
            if index == rootActiveIndex {
                btn.setTitleColor(AppConfig.sharedInstance.MAIN_TITLE_COLOR, for: .normal)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
            } else {
                btn.setTitleColor(AppConfig.sharedInstance.MAIN_GRAY_TITLE_COLOR, for: .normal)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
            }
            btn.addTarget(self, action: #selector(chooseRootItem(_:)), for: .touchUpInside)
            btn.tag = index + 100
            itemBgView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.left.right.top.bottom.equalToSuperview()
            }

            let bottomView = UIImageView.init(image: UIImage.init(named: "home_root_category_line"))
            bottomView.isHidden = !(index == rootActiveIndex)
            itemBgView.addSubview(bottomView)
            bottomView.snp.makeConstraints { (make) in
                make.width.equalTo(24)
                make.height.equalTo(4)
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview()
            }
        }
        
        let line = UIView.init()
        line.backgroundColor = AppConfig.sharedInstance.MAIN_BG_VIEW_COLOR
        rootBgView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(1)
        }
    }
    
    @objc func chooseRootItem(_ btn: UIButton) {
        rootActiveIndex = btn.tag - 100
        for item in 0..<rootScrollView.subviews.count {
            for i in rootScrollView.subviews[item].subviews {
                if i.isKind(of: UIImageView.self) {
                    i.isHidden = !(item == rootActiveIndex)
                }
                if i.isKind(of: UIButton.self) {
                    let btn:UIButton = i as! UIButton
                    if item == rootActiveIndex {
                        btn.setTitleColor(AppConfig.sharedInstance.MAIN_TITLE_COLOR, for: .normal)
                    } else {
                        btn.setTitleColor(AppConfig.sharedInstance.MAIN_GRAY_TITLE_COLOR, for: .normal)
                    }
                    btn.titleLabel?.font = (item == rootActiveIndex) ? UIFont.systemFont(ofSize: 16, weight: .semibold) : UIFont.systemFont(ofSize: 14, weight: .regular)
                }
            }
        }
        
        handleGetCategoryList(type: "second", pid: rootArr[rootActiveIndex].dictionaryObject!["id"] as! String)
    }
    
    // MARK: - 三级分类
    func reloadThirdView() {
        let bgView = thirdScrollView
        if thirdArr.count == 0 {
            thirdBgViewHeight.constant = 0
            thirdBgViewBottomHeight.constant = 0
        } else {
            thirdBgViewHeight.constant = 30
            thirdBgViewBottomHeight.constant = 16
        }
        
        for view in bgView.subviews {
            view.removeFromSuperview()
        }
        
        for index in 0..<thirdArr.count {
            let itemBgView = UIView.init()
            itemBgView.backgroundColor = AppConfig.sharedInstance.MAIN_LIGHT_COLOR
            itemBgView.layer.masksToBounds = true
            itemBgView.layer.cornerRadius = 6
            thirdScrollView.addSubview(itemBgView)
            if index == 0 {
                itemBgView.snp.makeConstraints { (make) in
                    make.top.bottom.equalToSuperview()
                    make.left.equalToSuperview()
                    make.height.equalTo(thirdBgView.snp.height)
                }
            } else if index == thirdArr.count - 1 {
                itemBgView.snp.makeConstraints { (make) in
                    make.right.equalToSuperview()
                    make.top.bottom.equalToSuperview()
                    make.left.equalTo(thirdScrollView.subviews[index - 1].snp.right).offset(12)
                    make.height.equalTo(thirdBgView.snp.height)
                }
            } else {
                itemBgView.snp.makeConstraints { (make) in
                    make.top.bottom.equalToSuperview()
                    make.left.equalTo(thirdScrollView.subviews[index - 1].snp.right).offset(12)
                    make.height.equalTo(thirdBgView.snp.height)
                }
            }
            
            let btn = UIButton.init(type: .custom)
            btn.setTitle(thirdArr[index]["name"].stringValue, for: .normal)
            if index == thirdActiveIndex {
                btn.setTitleColor(AppConfig.sharedInstance.MAIN_COLOR, for: .normal)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
            } else {
                btn.setTitleColor(AppConfig.sharedInstance.MAIN_GRAY_TITLE_COLOR, for: .normal)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .regular)
            }
            btn.addTarget(self, action: #selector(chooseThirdItem(_:)), for: .touchUpInside)
            btn.tag = index + 100
            itemBgView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(8)
                make.right.equalToSuperview().offset(-8)
                make.top.equalToSuperview().offset(6)
                make.bottom.equalToSuperview().offset(-6)
            }
        }
    }
    
    @objc func chooseThirdItem(_ btn: UIButton) {
        thirdActiveIndex = btn.tag - 100
        for item in 0..<thirdScrollView.subviews.count {
            for i in thirdScrollView.subviews[item].subviews {
                if i.isKind(of: UIButton.self) {
                    let btn:UIButton = i as! UIButton
                    if item == thirdActiveIndex {
                        btn.setTitleColor(AppConfig.sharedInstance.MAIN_COLOR, for: .normal)
                    } else {
                        btn.setTitleColor(AppConfig.sharedInstance.MAIN_GRAY_TITLE_COLOR, for: .normal)
                    }
                    btn.titleLabel?.font = (item == thirdActiveIndex) ? UIFont.systemFont(ofSize: 12, weight: .medium) : UIFont.systemFont(ofSize: 12, weight: .regular)
                }
            }
        }
        
        currentCoursePid = thirdArr[thirdActiveIndex]["id"].stringValue
        handleGetCourseListData()
    }
    
    // MARK: UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == secondTableView {
            return secondArr.count
        } else if tableView == courseTableView {
            return courseArr.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == secondTableView {
            let cell:UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "secondCell")
            cell.selectionStyle = UITableViewCell.SelectionStyle.none
            
            let item = secondArr[indexPath.row]
            
            let title = cell?.viewWithTag(1) as! UILabel
            title.text = item["name"].stringValue
            
            if (indexPath.row == secondActiveIndex) {
                title.textColor = AppConfig.sharedInstance.MAIN_COLOR
                title.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
                cell.contentView.backgroundColor = AppConfig.sharedInstance.MAIN_BG_VIEW_COLOR
                secondActiveTitle.text = title.text
            } else {
                title.textColor = AppConfig.sharedInstance.MAIN_GRAY_TITLE_COLOR
                title.font = UIFont.systemFont(ofSize: 13, weight: .regular)
                cell.contentView.backgroundColor = UIColor.white
            }
            return cell
        } else if tableView == courseTableView {
            let cell:UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "courseCell")
            cell.selectionStyle = UITableViewCell.SelectionStyle.none
            
            let item = courseArr[indexPath.row]
            let cover = cell?.viewWithTag(1) as! UIImageView
            let coverImageUrl = item["cover"].stringValue.imageSizeToThumbnail(contentView: cover)
            print("课程首页图片url：\(coverImageUrl)")
            cover.af.setImage(withURL: URL(string: coverImageUrl)!, placeholderImage: UIImage.init(named: "logo"))
            let name = cell?.viewWithTag(2) as! UILabel
            name.text = item["name"].stringValue
            let remark = cell?.viewWithTag(3) as! UILabel
            remark.text = item["remark"].stringValue
            let time = cell?.viewWithTag(4) as! UILabel
            time.text = item["lastModifiedDate"].stringValue.components(separatedBy: " ")[0]
            
            return cell
        }
        return UITableViewCell.init()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == secondTableView {
            secondActiveIndex = indexPath.row
            secondTableView.reloadData()
            
            handleGetCategoryList(type: "third", pid: secondArr[secondActiveIndex].dictionaryObject!["id"] as! String)
        } else if tableView == courseTableView {
            let courseDetail = UtilManager.sharedInstance.getVCFromSB(identifier: "CourseDetailViewController") as! CourseDetailViewController
            courseDetail.courseId = courseArr[indexPath.row].dictionaryObject!["id"] as! String
            self.navigationController?.pushViewController(courseDetail, animated: true)
        }
    }
    
    func refreshHomeData() {
        resetData()
        
        secondTableView.estimatedRowHeight = 50.0
        secondTableView.rowHeight = UITableView.automaticDimension
        secondTableView.tableFooterView = UIView.init()
        
        courseTableView.estimatedRowHeight = 141.0
        courseTableView.rowHeight = UITableView.automaticDimension
        courseTableView.tableFooterView = UIView.init()

        handleGetCategoryList(type: "root")
    }
    
    func resetData() {
        rootArr = JSON.init(parseJSON: "[]")
        reloadRootView()
        rootActiveIndex = 0
        
        secondArr = JSON.init(parseJSON: "[]")
        secondTableView.reloadData()
        secondActiveIndex = 0
        
        thirdArr = JSON.init(parseJSON: "[]")
        reloadThirdView()
        thirdActiveIndex = 0
        
        page = 1
        courseArr = JSON.init(parseJSON: "[]")
        courseTableView.reloadData()
    }
    
    @objc func loginStatus(noti : Notification){
        let status = noti.userInfo!["isLogin"] as! Bool
        print("loginStatus：\(status)")
        
        if status {
            refreshHomeData()
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let font = UIFont.systemFont(ofSize: 18.0, weight: .semibold)
        let textAttributes = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:UIColor.white]
        self.navigationController?.navigationBar.titleTextAttributes = textAttributes
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = AppConfig.sharedInstance.MAIN_COLOR
        
        courseTableView.estimatedRowHeight = 141.0
        courseTableView.rowHeight = UITableView.automaticDimension
        courseTableView.tableFooterView = UIView.init()
        courseTableView.mj_header = MJRefreshNormalHeader.init {[weak self] in
            self?.page = 1
            self?.handleGetCourseListData()
        }
        courseTableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
            self?.page = self!.page + 1
            self?.handleGetCourseListData()
        })
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            if !UserInfo.sharedInstance.isLogin() {
                UserInfo.sharedInstance.toLogin("normal")
            } else {
                self.refreshHomeData()
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginStatus), name: NSNotification.Name(rawValue:AppConfig.sharedInstance.LoginNotification), object: nil)
        
        rootScrollView.showsHorizontalScrollIndicator = false
        rootBgView.addSubview(rootScrollView)
        rootScrollView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        
        thirdScrollView.showsHorizontalScrollIndicator = false
        thirdBgView.addSubview(thirdScrollView)
        thirdScrollView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        
        let rightBarBtn = UIButton.init(type: .custom)
        rightBarBtn.setImage(UIImage.init(named: "sao"), for: .normal)
        rightBarBtn.addTarget(self, action: #selector(handleToScan), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBarBtn)
        
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
